package dhy.com;


import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <p>
 *     全局返回值结果处理,加了泛型表示只处理特定的返回值类型
 * </p>
 */
@Component
@Slf4j
public class GlobalReponseAdvice implements ResponseBodyAdvice {


    /**
     * <p>
     *     这个方法表示对于哪些请求要执行beforeBodyWrite，返回true执行，返回false不执行
     * </p>
     * @param methodParameter 方法相关信息
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
         log.info("aClass类型: "+aClass);
        return true;
    }

    /**
     * <p>
     *     对于返回的对象如果不是最终对象AjaxResponse，则选包装一下
     * </p>
     * @param o 方法返回的镀锡
     * @param methodParameter 方法参数
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(!(o instanceof AjaxResponse))
        {
            return AjaxResponse.success(o);
        }
        return o;
    }
}
